from actions.action import Action
from logger import logger
import re


class SelectAction(Action):

    def check(self, activity, config, driver):
        if "select_list" in config:
            activity.elements = _select(activity.elements, config["select_list"])
            logger.info(activity.elements)
        return False

    def run_next_acton(self):
        return True


def _select(elements, select_list):
    for key in list(elements):
        flag = False
        for filt in select_list:
            if _filt(elements[key], filt):
                flag = True
                break
        if flag is False:
            elements.pop(key)
    return elements


def _filt(element, filt):
    for k in filt:
        if k not in element:
            return False

        if isinstance(filt[k], str):
            if not re.match(filt[k], element[k]):
                return False
        else:
            if filt[k] != element[k]:
                return False

    return True
